﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace LocalOverride.Fiddler.Store
{
    [Serializable]
    public class FileExtensionList : ICollection<string>
    {
        readonly List<string> internalList = new List<string>();
        private static readonly Regex ValidItemRegex = new Regex("[0-9a-z]+", RegexOptions.IgnoreCase);

        public bool Equals(FileExtensionList other)
        {
            var thisHasAllOtherItems = this.All(other.Contains);
            var otherHasAllTheseItems = other.All(Contains);

            return thisHasAllOtherItems && otherHasAllTheseItems;
        }

        public IEnumerator<string> GetEnumerator()
        {
            return internalList.GetEnumerator();
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != typeof (FileExtensionList)) return false;
            return Equals((FileExtensionList) obj);
        }

        public override int GetHashCode()
        {
            return 0;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public static bool operator ==(FileExtensionList left, FileExtensionList right)
        {
            return Equals(left, right);
        }

        public static bool operator !=(FileExtensionList left, FileExtensionList right)
        {
            return !Equals(left, right);
        }

        public void Add(string item)
        {
            if(!ValidItemRegex.IsMatch(item))
            {
                throw new ArgumentException("Invalid character", item);
            }
            internalList.Add(item);
        }

        public void Clear()
        {
            internalList.Clear();
        }

        public bool Contains(string item)
        {
            return internalList.Contains(item);
        }

        public void CopyTo(string[] array, int arrayIndex)
        {
            internalList.CopyTo(array, arrayIndex);
        }

        public bool Remove(string item)
        {
            return internalList.Remove(item);
        }

        public int Count
        {
            get { return internalList.Count; }
        }

        public bool IsReadOnly
        {
            get { return ((ICollection<string>) internalList).IsReadOnly; }
        }
    }
}